package infiews.crawler;

import infiews.crawler.exceptions.CrawlerDatabaseException;
import infiews.crawler.exceptions.CrawlerException;
import infiews.fetch.PageFetcher;
import infiews.util.Database;
import infiews.util.Logger;
import infiews.web.Site;

public final class Crawler{

	public Crawler() throws CrawlerException {
		config = new Config();
        logger = new Logger();
        db = new Database();
		fetcher = new PageFetcher();
	}

	public void start() throws CrawlerException{
		String[] namespaces = getDb().getNamespaces();

		for(String namespace : namespaces){
			try{
				currentSiteName = namespace;
				CrawlerController controller = new CrawlerController();
				Site site = getDb().loadSite(namespace);
                Crawler.setCurrentSite(site);
				controller.start(site);
			}catch(Exception e){
				throw new CrawlerException("Unable to start crawler '" + namespace + "'");
			}
		}
	}


	public void addSite( Site site ) throws CrawlerDatabaseException{
		site.setActive(true);
		getDb().addSite(site);
	}
	
	public void updateSite( Site site ) throws CrawlerDatabaseException{
        if(getDb().hasSite(site))
        {
            getDb().saveSite(site);
        } else {
		    getDb().addSite(site);
        }
	}
	
	public void removeSite( String name ) throws CrawlerDatabaseException{
		getDb().removeSite(name);
	}
	
    public static Config getConfig(){
        return config;
    }

    public static Site getCurrentSite(){
        return currentSite;
    }

    public static void setCurrentSite(Site newSite){
        currentSite = newSite;
    }

    public static Logger log(){
        return logger;
    }

    public static Database getDb(){
        return db;
    }

	public static PageFetcher getFetcher(){
		return fetcher;
	}

    private static Config config;
    private static Logger logger;
	private static Database db;
	private static PageFetcher fetcher;
	public static String currentSiteName;
    private static Site currentSite;
}